#! /bin/bash

if [[ $EUID -ne 0 ]]; then
    echo "Error:This script must be run as root!" 1>&2
    exit 1
fi

echo "1.Prepare environment"
qcow2_img_path=./openeuler.qcow2
qemu_tool_path=/var/tmp/qemu_tool
rootfs_path=$qemu_tool_path/rootfs
dnf -y install libguestfs-tools libvirt
systemctl start libvirtd
echo

echo "2.Create rootfs"
rm -rf $rootfs_path
mkdir $rootfs_path
dnf --installroot=$rootfs_path -y --nogpgcheck install gnupg2 kernel iSulad network-scripts NetworkManager openssh-server dnf
echo "Rootfs created"
echo

echo "3.Mount the old qcow2 image"
guestmount -a openeuler.qcow2 -m /dev/sdb /mnt
echo "Mounted"
echo

echo "4.Remove too big directors"
rm -rf /mnt/usr
rm -rf /var
echo "Directors removed"

echo "5.Copy the rootfs to the mount point"
cp -rf $qemu_tool_path/usr /mnt
cp -rf $qemu_tool_path/var /mnt
echo "Copied"
echo

echo "6.Clean the environment"
umount /mnt
rm -rf $rootfs_path
echo "Finished"